package com.share.tool.generator.sql_convert.util;

import com.share.tool.generator.sql_convert.vo.Column;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class ConvertUtil {

    /**
     * 转为java的model
     *
     * @param tableName
     * @param columnList
     * @return
     */
    public static String toJavaModel(String tableName, List<Column> columnList) {
        //遍历结果
        StringBuffer javaField = new StringBuffer();
        javaField.append("");
        javaField.append("@Data" + System.lineSeparator());
        javaField.append("public class " + tableName + "{" + System.lineSeparator());
        for (Column col : columnList) {
            String type = col.getType();
            String javaType = "String";
            if (StringUtils.isNotBlank(type)) {
                if (type.contains("text")) {
                    javaType = "String";
                } else if (type.contains("bigint")) {
                    javaType = "Long";
                } else if (type.contains("int")) {
                    javaType = "Integer";
                } else if (type.contains("decimal")) {
                    javaType = "Double";
                } else if (type.contains("timestamp")) {
                    javaType = "Date";
                }
            }
            //javaField
            String item = "private  " + javaType + " " + col.getColumnCamel() + ";";
            javaField.append(item + System.lineSeparator());
        }
        javaField.append("}");

        return javaField.toString();
    }

    /**
     * mysql转为sqlite
     *
     * @param tableName
     * @param columnList
     * @return
     */
    public static String createSqliteTable(String tableName, List<Column> columnList) {
        String createTable = "CREATE TABLE #tableName# (\n" +
                "       #columns#" +
                ");";
        String columns = columnList.stream().map(e -> {
            String type = "text";
            String t = e.getType();
            if (t != null && (t.contains("int") || t.contains("bit"))) {
                type = "number";
            }
            return e.getColumn() + " " + type;
        }).collect(Collectors.joining("," + System.lineSeparator()));
        String sql = createTable.replaceAll("#tableName#", tableName)
                .replaceAll("#columns#", columns);
        return sql;
    }

    /**
     * <insert id="insertbatch" parameterType="java.util.List">
     * insert into ts_strategy_result (
     * code,name,industry_name,date,time,price,status,strategy
     * )
     * VALUES
     * <foreach collection="list" index="index" item="item" separator=",">
     * (
     * #{item.code},#{item.name},#{item.industryName},#{item.date},#{item.time},#{item.price},#{item.status},#{item.strategy}
     * )
     * </foreach>
     * </insert>
     *
     * @param tableName
     * @param columnList
     * @return
     */
    public static String insertbatch(String tableName, List<Column> columnList) {
        String insertbatch = "    <insert id=\"insertbatch\" parameterType=\"java.util.List\">\n" +
                "        insert into #tableName# (\n" +
                "        #columns# \n" +
                "        )\n" +
                "        VALUES\n" +
                "        <foreach collection=\"list\" index=\"index\" item=\"item\" separator=\",\">\n" +
                "            (\n" +
                "           #javaFiles# \n" +
                "            )\n" +
                "        </foreach>\n" +
                "    </insert>";
        String columns = columnList.stream().map(e -> e.getColumn()).collect(Collectors.joining(","));
        String javaFiles = columnList.stream().map(e -> "#{item." + e.getColumnCamel() + "}").collect(Collectors.joining(","));
        String sql = insertbatch.replaceAll("#columns#", columns)
                .replaceAll("#tableName#", tableName)
                .replaceAll("#javaFiles#", javaFiles);
        return sql;
    }


    /**
     * <update id="updateByCode">
     * update ts_strategy_result
     * <set>
     * <if test="record.name != null and record.name !=''">
     * name = #{record.name},
     * </if>
     * <if test="record.time != null and record.time !=''">
     * time = #{record.time},
     * </if>
     * </set>
     * where code = #{record.code}
     * </update>
     *
     * @param tableName
     * @param columnList
     * @return
     */
    public static String updateIfTestById(String tableName, List<Column> columnList) {
        String ifTestValue = getIfTestValue(columnList);
        String tmpleate = "<update id=\"updateByCode\">\n" +
                "       update #tableName#\n" +
                "       <set>\n" +
                "           #ifTest#\n" +
                "       </set>\n" +
                "       where id = #{record.id}\n" +
                "</update>";
        String sql = tmpleate.replaceAll("#tableName#", tableName)
                .replaceAll("#ifTest#", ifTestValue);
        return sql;
    }

    public static String insertIfTest(String tableName, List<Column> columnList) {
        //生成插入sql语句
        String ifTestColumn = getIfTestColumn(columnList);
        String ifTestValue = getIfTestValue(columnList);
        String templeate = "INSERT INTO #tableName# ( \n" +
                "       #ifTestColumn# \n" +
                ") values ( \n" +
                "       #ifTestValue# \n" +
                ")\n";

        String tmp = templeate.replaceAll("#tableName#", tableName)
                .replaceAll("#ifTestColumn#", ifTestColumn)
                .replaceAll("#ifTestValue#", ifTestValue);

        return tmp;
    }

    // 删除重复数据
    public static String deleteByIdAndCode(String tableName, List<Column> columnList) {
        String delTempleate = "DELETE t1 FROM {table} AS t1 LEFT JOIN(SELECT max(id) AS id,code,`date`,count(1) AS num FROM {table} GROUP BY code,`date` HAVING num >=2) AS t2 ON t1.code = t2.code and t1.date=t2.date WHERE t1.id  <![CDATA[ > ]]>  t2.id";
        String delSql = delTempleate.replaceAll("\\{table\\}", tableName);
        return delSql;
    }

    private static String getIfTestValue(List<Column> columnList) {
        List<String> reList = new LinkedList<>();
        String templeate = "<if test=\"record.#javaField# != null and record.#javaField# !=''\"> #column# = #{record.#javaField#}, </if>";
        for (Column e : columnList) {
            String tmpSql = templeate.replaceAll("#javaField#", e.getColumnCamel())
                    .replaceAll("#column#", e.getColumn());
            reList.add(tmpSql);
        }
        return reList.stream().collect(Collectors.joining(System.lineSeparator()));
    }

    private static String getIfTestColumn(List<Column> columnList) {
        List<String> reList = new LinkedList<>();
        String templeate = "<if test=\"record.#javaField# != null and record.#javaField# !=''\"> #column# , </if>";
        for (Column e : columnList) {
            String tmpSql = templeate.replaceAll("#javaField#", e.getColumnCamel())
                    .replaceAll("#column#", e.getColumn());
            reList.add(tmpSql);
        }
        return reList.stream().collect(Collectors.joining(System.lineSeparator()));
    }
}
